using System;

namespace FluentBinding.WinForms
{
    /// <typeparam name="E">Type of the root entity</typeparam>
    /// <typeparam name="TSelected">Type of the selected entity</typeparam>
    internal class DataSourceEntityAdapterConvertor<E, TSelected> : IDataMemberConvertor<E>
        where TSelected : class
    {
        #region Fields

        private readonly Action<E, TSelected> _initializer;
        private readonly Func<E, TSelected> _selector;

        #endregion

        #region Ctor

        public DataSourceEntityAdapterConvertor(Func<E, TSelected> selector)
            : this(selector, null)
        {
        }

        public DataSourceEntityAdapterConvertor(Func<E, TSelected> selector, Action<E, TSelected> initializer)
        {
            _selector = selector;
            _initializer = initializer;
        }

        #endregion

        #region IDataMemberConvertor<E> Members

        public object Select(E entity)
        {
            TSelected selected = _selector(entity);
            return new DataSourceEntityAdapter<TSelected>(selected);
        }

        public void Initialize(E entity, object value)
        {
            if (_initializer != null)
            {
                _initializer(entity, value == null ? null : ((DataSourceEntityAdapter<TSelected>)value).Entity);
            }
        }

        #endregion
    }
}